package API.ObjectsAPI;

import java.util.Objects;

class Test{
    private int a;

    public Test(int a){
        this.a = a;
    }

    public Test(){
    }

    @Override
    //重写equals方法
    public boolean equals(Object obj){
        if(obj instanceof Test test)
            return test.a == this.a;
        return false;
    }
}

public class equals {
    public static void main(String[] args) {
        Object obj1 = null;
        Object obj2 = new Object();
        Object obj3 = new Object();
        Object obj4 = obj2;
        System.out.println(obj2.equals(obj1));
        //使用下方表达式会报错，因为obj1指向一个空指针
        //obj1.equals(obj2);
        //Objects中的equals方法会事先判断第一个参数是否为空指针
        System.out.println(Objects.equals(obj1, obj2));
        System.out.println(Objects.equals(obj2, obj3));
        System.out.println(Objects.equals(obj2, obj4));
        //Objects.equals方法源代码
        //public static boolean equals(Object a, Object b) {
        //  return (a == b) || (a != null && a.equals(b));
        //}
        Test test1 = new Test(1);
        Test test2 = new Test(1);
        System.out.println(test1 == test2);
        //由于Test类中重写了equals方法，根据相应逻辑，输出true
        System.out.println(Objects.equals(test1, test2));
    }
}
